﻿// /****************************************************************************************************************************
//  * 项目名称： 
//  * 类 名 称：LicaiCenterTrainService
//  * 功能说明：
//  * 版    本：0.0.1
//  * 作    者：史垚祎
//  * 邮    箱：396038130@qq.com
//  * 创建时间：2024/7/8 15:24
//  * 更新人：
//  * 更新时间：
//  * 更新说明：
// /****************************************************************************************************************************/
//
using System;
using NP.BPMReportPlatform.AuxiliaryMaterial.Dto;
using System.Collections.Generic;
using System.Threading.Tasks;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using NP.BPMReportPlatform.Licai.Dto;
using System.Linq;

namespace NP.BPMReportPlatform.Licai
{
    public class LicaiCenterTrainService : BPMReportPlatformAppService, ILicaiCenterTrainService
    {
        readonly SqlSugarClient _db;
        readonly SqlSugarClient _dbPlatform;
        readonly IBPMUtilsAppService _bPMUtilsApp;
        readonly IBPMPlatformAppService _iBPMPlatformApp;
        public LicaiCenterTrainService(ISqlSugarAppService sqlSugarAppService,
            IBPMUtilsAppService bPMUtilsApp, IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<LicaiCenterTrainOutPut>> GetAllAsync(GetLicaiCenterTrainInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceId, userId));
            SetStatusName(listViewDto);
            return new PagedResultDto<LicaiCenterTrainOutPut>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<LicaiCenterTrainOutPut>> ExportAsync(GetLicaiCenterTrainInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            SetStatusName(listViewDto);
            return listViewDto;
        }

        void SetStatusName(List<LicaiCenterTrainOutPut> list)
        {
            var aList = _dbPlatform.Queryable<Dictionaries>().Where(x => x.TypeCode == "LicaiArea").ToList();
            if (list != null && list.Any())
            {
                list.ForEach(item =>
                {
                    string name = "";
                    switch (item.Status)
                    {
                        case -1:
                            name = "未通过";
                            break;
                        case 0:
                            name = "待审核";
                            break;
                        case 1:
                            name = "已通过";
                            break;
                        case -2:
                            name = "草稿";
                            break;
                        default:
                            name = "-";
                            break;
                    }
                    item.StatusName = name;
                    item.Area = aList.FirstOrDefault(x => x.Code == item.Area)?.Name ?? "-";
                });
            }
        }

        private ISugarQueryable<LicaiCenterTrainOutPut> GetQueryable(GetLicaiCenterTrainInput input)
        {
            #region 发起时间
            var SubmitDateEnd = DateTime.Now;
            var SubmitDateStrat = DateTime.Now;
            if (input.ApplyStartDate.HasValue)
            {
                SubmitDateStrat = input.ApplyStartDate.Value;
            }
            if (input.ApplyEndDate.HasValue)
            {
                SubmitDateEnd = input.ApplyEndDate.Value.AddDays(1);
            }
            #endregion
            #region 审核时间
            var auditDateEnd = DateTime.Now;
            var auditDateStrat = DateTime.Now;
            if (input.AuditStartDate.HasValue)
            {
                auditDateStrat = input.AuditStartDate.Value;
            }
            if (input.AuditEndDate.HasValue)
            {
                auditDateEnd = input.AuditEndDate.Value.AddDays(1);
            }
            #endregion
            #region 开课时间
            var openDateEnd = DateTime.Now;
            var openDateStrat = DateTime.Now;
            if (input.ClassStartDate.HasValue)
            {
                openDateStrat = input.ClassStartDate.Value;
            }
            if (input.ClassEndDate.HasValue)
            {
                openDateEnd = input.ClassEndDate.Value.AddDays(1);
            }
            #endregion

            var noList = new List<string>();
            if (!string.IsNullOrEmpty(input.InstanceId))
            {
                noList = input.InstanceId.Split(new char[] { ',', ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }


            var uQuery = _dbPlatform.Queryable<Users>()
                .WhereIF(!string.IsNullOrEmpty(input.UserName), x => x.UserName.Contains(input.UserName) || x.WorkNumber == input.UserName).AS("BPM_Platform.Users");
            var pQuery = _db.Queryable<BusinessProcessesNew>()
                .WhereIF(input.ApplyStartDate.HasValue, x => x.StartTime >= SubmitDateStrat)
                .WhereIF(input.ApplyEndDate.HasValue, x => x.StartTime < SubmitDateEnd)
                .WhereIF(input.AuditStartDate.HasValue, x => x.FinishTime >= auditDateStrat)
                .WhereIF(input.AuditEndDate.HasValue, x => x.FinishTime < auditDateEnd);

            var nStatus = input.Status.HasValue ? input.Status.Value : 0;

            var tQuery = _db.Queryable<LicaiCenterTrainHeader>()
                .WhereIF(!string.IsNullOrEmpty(input.InstanceId), x => noList.Contains(x.InstanceNumber))
                .WhereIF(!string.IsNullOrEmpty(input.CourseCode), x => x.CourseCode.Contains(input.CourseCode))
                .WhereIF(!string.IsNullOrEmpty(input.CourseName), x => x.CourseName.Contains(input.CourseName))
                .WhereIF(!string.IsNullOrEmpty(input.Area), x => x.Area == input.Area)
                .WhereIF(input.ClassStartDate.HasValue, x => x.ClassStartDate >= openDateStrat)
                .WhereIF(input.ClassEndDate.HasValue, x => x.ClassEndDate < openDateEnd)
                .WhereIF(input.Status.HasValue, x => x.LCTStatus == nStatus);


            var query = tQuery.InnerJoin(pQuery, (t, p) => p.InstanceId == t.InstanceNumber)
                    .InnerJoin(uQuery, (t, p, u) => p.StartUserId == u.UserId)
                    .OrderBy((t, p, u) => p.StartTime, OrderByType.Desc)
                    .Select((t, p, u) => new LicaiCenterTrainOutPut()
                    {
                        InstanceId = p.InstanceId,
                        CreateDate = p.StartTime,
                        StartUserName = p.StartUserName,
                        Area = t.Area,
                        CourseCode = t.CourseCode,
                        CourseName = t.CourseName,
                        RealStudentCount = t.RealStudentCount,
                        SapOrderNo = t.SapOrderNo,
                        SinglePrice = t.SinglePrice,
                        TotalTaxActualAmount = t.TotalTaxActualAmount,
                        Status = t.LCTStatus,
                        PayeeUnit = t.PayeeUnit,
                        RealSession = t.RealSession,
                        TeacherCount = t.TeacherCount
                    });
            return query;
        }

    }
}

